package com.mfsoft.camera;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.inputmethodservice.InputMethodService.Insets;
import android.net.ParseException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.CalendarContract.Instances;
import android.provider.ContactsContract;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView.Validator;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.plus.model.people.Person;
import com.mfsoft.camera.R;
import com.mfsoft.model.CameraModel;
import com.mfsoft.model.UserActions;
import com.mfsoft.net.MyFunctions_THI;
import com.mfsoft.utilities.Utility;

public class RegisterActivity extends Activity {

	// protected static final String CharSequence = null;
	public CameraModel cameraModel;
	public CameraApp instance;
	Button btndangky;
	EditText edthoten, edtdangnhap, edtdiachimail, edtmatkhau,
			edtconfirmpassword;

	RadioButton rdbnam, rdbnu;
	Calendar lich = Calendar.getInstance();
	SimpleDateFormat sdf;
	int typengay;
	String resultText;
	RadioGroup radioGroup;
	int gender;
	AlertDialog.Builder mydialog;
	private PlusClient mPlusClient;
	// đặt tên cho tập tin lưu trạng thái
	String prefname = "my_data";
	public UserActions userAction;
	private ImageButton btnBirthday;
	private TextView tvBirthday, tvgender;
	public static final String GMAIL = "gmail";
	public static final String BIRTHDAY = "birthday";
	public static final String NICKNAME = "nickname";
	public static final String USERNAME = "username";
	public static final String GENDER = "gender";
	public static final String PASSWORD = "password";
	public static final String TYPE = "type";
	public static final String USERID = "userid";
	public static final String AVATAR = "avatar";
	public static final String PAGE = "page";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register_activity__thi);
		edthoten = (EditText) findViewById(R.id.edthoten);
		btnBirthday = (ImageButton) findViewById(R.id.btnbirthday);
		edtdangnhap = (EditText) findViewById(R.id.edtdangnhap);
		edtdiachimail = (EditText) findViewById(R.id.edtdaichimail);
		edtmatkhau = (EditText) findViewById(R.id.edtmatkhau);
		edtconfirmpassword = (EditText) findViewById(R.id.edtconfirmpassword);
		btndangky = (Button) findViewById(R.id.btndangky);
		rdbnam = (RadioButton) findViewById(R.id.rdbnam);
		rdbnu = (RadioButton) findViewById(R.id.rdbnu);
		tvBirthday = (TextView) findViewById(R.id.txtbirthdayfill);
		tvgender = (TextView) findViewById(R.id.txtgender);
		sdf = new SimpleDateFormat("yyyy-MM-dd");
		sdf.setLenient(true);

		// hideSoftKeyboard(edtdangnhap.getText(),edtdiachimail.getText());
		// ---RadioButton---
		radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
		if (rdbnam.isChecked() == true) {

			tvgender.setText("Nam");
		} else {

			tvgender.setText("Nữ");
		}
		btndangky.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (check()) {

					SharedPreferences pre = getSharedPreferences("my_data",
							MODE_PRIVATE);
					ThucThiRegister register = new ThucThiRegister();
					if (register.getStatus() == AsyncTask.Status.PENDING) {

						register.execute();

					}
					onBackPressed();
				}
				/*
				 * if(rdbnam.isChecked() == true)
				 * 
				 * gender = 1;
				 * 
				 * else gender = 0; Thread thread = new Thread() {
				 * 
				 * @Overrides public void run() { // TODO Auto-generatedoi
				 * method stub HttpClient httpClient = new DefaultHttpClient();
				 * HttpPost httpPost = new
				 * HttpPost(MyFunctions_THI.registerurl);
				 * 
				 * try { Log.w("test 1", "test 1"); List<NameValuePair>
				 * nameValuePairs = new ArrayList<NameValuePair>();
				 * nameValuePairs.add(new BasicNameValuePair("command",
				 * "register")); nameValuePairs.add(new
				 * BasicNameValuePair("gmail",
				 * edtdiachimail.getText().toString())); nameValuePairs.add(new
				 * BasicNameValuePair("password",
				 * edtmatkhau.getText().toString())); nameValuePairs.add(new
				 * BasicNameValuePair("birthday",
				 * edtngaysinh.getText().toString())); nameValuePairs.add(new
				 * BasicNameValuePair("nickname",
				 * edthoten.getText().toString())); nameValuePairs.add(new
				 * BasicNameValuePair("username",
				 * edtdangnhap.getText().toString())); nameValuePairs.add(new
				 * BasicNameValuePair("gender", String.valueOf(gender)));
				 * httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				 * 
				 * HttpResponse response = httpClient.execute(httpPost);
				 * HttpEntity entity = response.getEntity();
				 * 
				 * if(entity!=null) { Log.w("test 1", "test 2"); InputStream
				 * inputStream = entity.getContent(); String result =
				 * getContent(inputStream);
				 * 
				 * try { char[] charArray = result.toCharArray(); String[]
				 * resultArray = new String[charArray.length]; for(int i=0;
				 * i<charArray.length;i++) { resultArray = charArray[i]; } final
				 * JSONObject info = new JSONObject(resultArray[1].trim());
				 * //tv.setText("dang ky thanh cong " +
				 * info.getString("gmail")); Log.w("info", info+""); //
				 * JSONArray jsonArray = new JSONArray(result); //
				 * ArrayList<HashMap<String, String>> jsonReturn = new
				 * ArrayList<HashMap<String,String>>(); // for(int i=0;
				 * i<jsonArray.length(); i++) { // JSONObject info =
				 * jsonArray.getJSONObject(i); // HashMap<String, String>
				 * jsonMap = new HashMap<String, String>(); //
				 * jsonMap.put("gmail", info.getString("gmail")); //
				 * jsonReturn.add(jsonMap); // } // Log.w("jsonReturn",
				 * jsonReturn+""); } catch (JSONException e) {
				 * Log.w("JSONException", e.getMessage()); // switch (result) {
				 * // case 0: // tv.setText("dang ky thanh cong"); // break; //
				 * // default: // break; // } } } } catch
				 * (ClientProtocolException e) {
				 * 
				 * } catch (IOException e) {
				 * 
				 * } } }; thread.start();
				 */
			}
		});
		btnBirthday.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				typengay = 1;
				showdate();
			}
		});

	}

	private static String getContent(InputStream inputStream)
			throws IOException {
		StringBuilder builder = new StringBuilder();
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(inputStream));
		String line = null;
		while ((line = bufferedReader.readLine()) != null) {
			builder.append(line).append("\n");
		}
		bufferedReader.close();
		return builder.toString().trim();
	}

	class ThucThiRegister extends AsyncTask<Void, Void, String> {

		String hoten, tendangnhap, diachiemail, pasword, gender, ngaysinh;
		MyFunctions_THI myfunctions_thi;

		private ProgressDialog progress;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress = ProgressDialog.show(RegisterActivity.this, "",
					getResources().getString(R.string.logining), true);
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			hoten = edthoten.getText().toString();
			tendangnhap = edtdangnhap.getText().toString();
			diachiemail = edtdiachimail.getText().toString();
			pasword = edtmatkhau.getText().toString();
			pasword = Utility.md5(pasword);
			if (rdbnam.isChecked() == true) {
				gender = "1";
				tvgender.setText(R.string.nam);
			} else {
				gender = "0";
				tvgender.setText(R.string.nu);
			}
			ngaysinh = tvBirthday.getText().toString();
			String thanhcong = "-1";
			Log.d(thanhcong, "loi");
			try {
				myfunctions_thi = new MyFunctions_THI(getApplicationContext());
				JSONObject jsonObject = myfunctions_thi.registerUser(hoten,
						tendangnhap, diachiemail, pasword, gender, ngaysinh);
				return jsonObject.toString();

			} catch (Exception e) {
				Log.d("loi",
						"Khong tao duoc json khong dang ky duoc" + e.toString());
			}
			return thanhcong;

		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			progress.dismiss();
			// JSONArray jsonarray = new JSONArray(String j);
			JSONObject json;
			try {
				json = new JSONObject(result);
				String resultJson = json.getString("result");
				if (resultJson.equalsIgnoreCase("-1")) {
					// gmail exist. json tra ve la -1 nen no chay vao ham nay.
					// tuc la gmail da ton tai. ok. duoc chua
					Log.w("action", "mail da dang ky");
					edtdiachimail.setError("Địa Chỉ Mail Này Đã Được Đăng Ký");
					edtdiachimail.requestFocus();
					setEditTextFocus(edtdiachimail, true);
				} else if (resultJson.equalsIgnoreCase("0")) {
					// nickname exist
					Log.w("action", "nick da dang ky");
					edtdangnhap.setError("Nick Name Đã Được Đăng Ký");
					edtdangnhap.requestFocus();
					setEditTextFocus(edtdangnhap, true);
				} else if (resultJson.equalsIgnoreCase("2")) {
					// serever is busy
					Log.w("action", "server khong phan hoi");
					mydialog.setMessage("Bạn Kiểm tra đã mở mạng chưa");
					mydialog.setIcon(R.drawable.ic_launcher);
					mydialog.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									// Toast.makeText(getApplicationContext(),"Ban vua nhap OK",
									// Toast.LENGTH_SHORT).show();

								}
							});

					// Showing Alert Message
					mydialog.show();

				} else {

					Log.w("action", json + "");
					JSONObject obj = json.getJSONArray("result").getJSONObject(
							0);
					String userId = obj.getString("userid");// theo json
															// response ve.
															// tuong tu parse
															// may cai kia'
					// tao doi tuong getSharedPreferences
					SharedPreferences pre = getSharedPreferences(prefname,
							MODE_PRIVATE);
					// tao doi tuong Editor de luu thay doi
					SharedPreferences.Editor editor = pre.edit();
					editor.putString("userId", userId);
					editor.putString("hoten", hoten);
					editor.putString("tendangnhap", tendangnhap);
					editor.putString("diachiemail", diachiemail);
					editor.putString("pasword", pasword);
					editor.putString("gender", gender);
					editor.putString("ngaysinh", ngaysinh);
					editor.commit();

					/*
					 * Intent login = new Intent(getApplicationContext(),
					 * MainActivity.class); startActivityForResult(login, 15);
					 */
					new AlertDialog.Builder(RegisterActivity.this)
							.setTitle(
									getResources().getString(
											R.string.successtitleregister))
							.setMessage(
									getResources().getString(
											R.string.successmessageregister))
							.setPositiveButton(
									getResources().getString(R.string.ok),
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											setResult(RESULT_OK);
											finish();
										}
									}).show();

				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	protected void hideSoftKeyboard(EditText input) {
		input.setInputType(0);
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(input.getWindowToken(), 0);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.register_activity__thi, menu);
		return true;
	}

	private boolean validateEmailAddress(String emailAddress) {

		if (Build.VERSION.SDK_INT >= 8) {
			return android.util.Patterns.EMAIL_ADDRESS.matcher(emailAddress)
					.matches();
		}

		Pattern pattern;
		Matcher matcher;
		String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		pattern = Pattern.compile(EMAIL_PATTERN);
		matcher = pattern.matcher(emailAddress);

		return matcher.matches();

	}

	// kiem tra passwor
	public boolean checkPassWordAndConfirmPassword(String password,
			String confirmPassword) {
		boolean pstatus = false;
		password = edtmatkhau.getText().toString().trim();
		confirmPassword = edtconfirmpassword.getText().toString().trim();
		if (confirmPassword != null && password != null) {
			if (password.equals(confirmPassword)) {
				pstatus = true;
			}
		}
		return pstatus;
	}

	public void showdate() {
		DatePickerDialog dpdialog = new DatePickerDialog(this,
				new OnDateSetListener() {

					@Override
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						// TODO Auto-generated method stub
						/*
						 * String ngay = dayOfMonth + "/" + (monthOfYear + 1) +
						 * "/" + year;
						 */
						String ngay = year + "-" + (monthOfYear + 1) + "-"
								+ dayOfMonth;
						switch (typengay) {
						case 1:
							tvBirthday.setText(ngay);
							break;

						}
					}
				}, lich.get(Calendar.YEAR), lich.get(Calendar.MONTH),
				lich.get(Calendar.DAY_OF_MONTH));
		dpdialog.show();
	}

	public boolean check() {
		boolean isOk = true;
		if (edthoten.getText().toString().equals("")) {
			edthoten.setError("Bạn Chưa Nhập Họ Và Tên");
			edthoten.requestFocus();
			setEditTextFocus(edthoten, true);
			isOk = false;
		} else if (edtdangnhap.getText().toString().equals("")) {
			edtdangnhap.setError("Bạn Chưa Nhập Tên Đăng Nhập");
			edtdangnhap.requestFocus();
			setEditTextFocus(edtdangnhap, true);
			isOk = false;
		} else if ((edtdangnhap.length()) < 6) {
			edtdangnhap.setError("ten dang nhap phai lon hon  6 ky tu");
			edtdangnhap.requestFocus();
			setEditTextFocus(edtdangnhap, true);
			isOk = false;
		} else if (edtdiachimail.getText().toString().equals("")) {
			edtdiachimail.setError("Bạn Chưa Nhập Địa Chỉ Email");
			edtdiachimail.requestFocus();
			setEditTextFocus(edtdiachimail, true);
			isOk = false;
		} else if (!validateEmailAddress(edtdiachimail.getText().toString()
				.trim())) {
			edtdiachimail.setError("Địa Chỉ Email không đúng");
			edtdiachimail.requestFocus();
			setEditTextFocus(edtdiachimail, true);
			isOk = false;
		} else if (edtmatkhau.getText().toString().equals("")) {
			edtmatkhau.setError("Bạn Chưa Nhập Mật Khẩu");
			edtmatkhau.requestFocus();
			setEditTextFocus(edtmatkhau, true);
			isOk = false;
		} else if ((edtmatkhau.length()) < 6) {
			edtmatkhau.setError("Mat khau phai tu 6 ky tu tro len");
			edtmatkhau.requestFocus();
			setEditTextFocus(edtmatkhau, true);
			isOk = false;
		} else if (!checkPassWordAndConfirmPassword(edtmatkhau.getText()
				.toString(), edtconfirmpassword.getText().toString()))

		{
			edtmatkhau.setText("");
			edtconfirmpassword.setText("");
			edtmatkhau.setError("Mật khẩu không trùng khớp");
			edtmatkhau.requestFocus();
			setEditTextFocus(edtmatkhau, true);
			isOk = false;
		} else if (tvBirthday.getText().toString().equals("")) {
			typengay = 1;
			isOk = false;
			showdate();
		}

		/*
		 * Person person = mPlusClient.getCurrentPerson(); if(person!=null &&
		 * person.hasBirthday()) { ngay = person.getBirthday(); } else {
		 * edtngaysinh.setError("ngay sinh khong dung"); }
		 */
		return isOk;
	}

	public void setEditTextFocus(EditText et, boolean isFocused) {
		et.setCursorVisible(isFocused);
		et.setFocusable(isFocused);
		et.setFocusableInTouchMode(isFocused);
		if (isFocused) {
			et.requestFocus();
		}
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show
	}
}
